<?php
/**
 * 获取产品数据写入数据库
 * Created by wzb.
 * User: wzb
 * time:2017/08/21
 */

/************处理产品信息*******************/
require("/home/ryerp_api/DB.php");
require("/home/ryerp_api/interface.php");
$app_info = "select * from dlz_account_info where status='1'";
$query = $db->query($app_info);//返回影响了多少行数据
while($row = $query->fetch()){
        $id_m = $row['id'];
//        if($id_m !== '2'){
//            continue;
//        }
        $store_name_m = $row['store_name'];
        $token_m = $row['token'];
        $baseUrl_m = $row['baseUrl'];
        $username_m = $row['username'];
        $password_m = $row['password'];
        $Mazentop = new Mazentop($token_m,$baseUrl_m,$username_m,$password_m);
        Getproductinfo($Mazentop,$id_m,$store_name_m,$db);
    }

//获取类目
function getcagatory($Mazentop){
    $productcag = $Mazentop->getcatalog();
    $productcag_arr = $productcag['items'];
    $newcatgaarray = array();
    foreach ($productcag_arr as $key => $value) {
        $attribute_set_id = $value['attribute_set_id'];
        $attribute_set_name = $value['attribute_set_name'];
        $newcatgaarray[$attribute_set_id] = $attribute_set_name;
    }
    return $newcatgaarray;
}

// 获取属性
function getattrdetail($Mazentop,$attrvalue){
    $attrnamearr = $Mazentop->getproductAttributeCode($attrvalue);
    $newcatgaarray = array();
    foreach ($attrnamearr as $key => $value) {
            $texture_label = isset($value['label'])?$value['label']:'';
            $texture_value = isset($value['value'])?$value['value']:'';
        $newcatgaarray[$texture_value] = $texture_label;
    }

    return $newcatgaarray;
}
function Getproductinfo($Mazentop,$id_m,$store_name_m,$db){
        echo "获取类目\n";

        $cagaty = getcagatory($Mazentop);

        echo "获取颜色属性\n";
        $colorarry = getattrdetail($Mazentop,'color');

        echo "获取花型属性\n";
        $texturearry = getattrdetail($Mazentop,'texture');

        echo "获取打包方式属性\n";
        $items_packagearry = getattrdetail($Mazentop,'items_package');

        echo "获取国家属性\n";
        $country_typearry = getattrdetail($Mazentop,'type');

        echo "获取等级属性\n";
        $gradearry = getattrdetail($Mazentop,'grade');

        echo "获取lace尺寸属性\n";
        $lace_sizearry = getattrdetail($Mazentop,'lace_size');

        echo "获取密度属性\n";
        $densityarry = getattrdetail($Mazentop,'density');

        echo "获取cap_size大小属性\n";
        $sizearry = getattrdetail($Mazentop,'cap_size');
   
        $getproduct = $Mazentop->Getproduct($pageSize=1,$currentPage=1);
        $totalnums = $getproduct['total_count'];//总数量 233
        echo "***************$store_name_m:get product numbers:$totalnums*********************\n";
        $result_fol = $totalnums/100;
        $pagenum = ceil($result_fol);//— 进一法取整
        $pageSize = "100";//每页显示多少
        
        /*获取上次同步数据*/
        $UpdateTime = date('Y-m-d H:i:s');
        for ($i = 1; $i <= "$pagenum"; $i++) {
            
            echo "*************start get product $i*******************\n";
            $getproducts = $Mazentop->Getproduct($pageSize,$currentPage="$i");
            $getproduct_arr = $getproducts['items'];
            $zuzhuangarrary = array();
            foreach ($getproduct_arr as $key => $value) {
                unset($zuzhuangarrary);
                $zuzhuangarrary['store_id'] =  $id_m;
                $zuzhuangarrary['store_name'] =  $store_name_m;
                $product_id = $value['id'];
                $zuzhuangarrary['product_id'] =  $product_id;
                $sku = $value['sku'];
                $zuzhuangarrary['sku'] =  $sku;
                $zuzhuangarrary['UpdateTime'] =  $UpdateTime;
                $name = str_replace('\'','\\\'',$value['name']);//部分名字中包含单引号,这里进行转换
                $zuzhuangarrary['name'] =  $name;
                $storeid_sku = $id_m.'-'.$sku;
                $zuzhuangarrary['storeid_sku'] = $storeid_sku; 
                $attribute_set_id = $value['attribute_set_id'];//属性id
                $category = $cagaty[$attribute_set_id];
                //$product_category = $Mazentop->getattributeSetId($attributeSetId=$attribute_set_id);
               // $category = $product_category['attribute_set_name'];//类目

                $zuzhuangarrary['attribute_set_id'] =  $category;
//				if(array_key_exists('price',$value)){
//					echo '<pre>'; var_dump(['price不存在'=>$value]); echo '</pre>';
//					continue;
//				}
                $price =(string)$value['price'];
                $zuzhuangarrary['price'] =  $price;
                $status = $value['status'];
                $zuzhuangarrary['status'] =  $status;
                $created_at = $value['created_at'];
                $zuzhuangarrary['created_at'] =  $created_at;
                $updated_at = $value['updated_at'];
                $zuzhuangarrary['updated_at'] =  $updated_at;
//                if(array_key_exists('weight',$value)){
//                	echo '<pre>';var_dump(['weight不存在'=>$value]); echo '</pre>';
//					continue;
//				}
                $weight = (string)$value['weight'];
                $zuzhuangarrary['weight'] =  $weight;
                echo "*************start sku:$sku*******************\n";
                //postsku_getproductopptionid($Mazentop,$sku,$db,$storeid_sku);
                /***扩展属性****/
                $custom_attributes = $value['custom_attributes'];
                echo '扩展信息';print_r($custom_attributes);
                /***************添加 修改 产品详情中的属性**********************/
                echo "----------get different attribute--------------\n";
                foreach ($custom_attributes as $keys => $values) {
                    
                    $attribute_code = $values['attribute_code'];

                    $value_value = $values['value'];
                    if("$attribute_code" == "texture"){
                        $texture = $texturearry[$value_value];
                        //$texture = attribute($Mazentop,$attribute_code,$value_value);//花型
                         $zuzhuangarrary['texture'] =  $texture;
                         echo '花型详细信息'; print_r($texturearry); echo "\n";
                         echo "花型$texture\n";
                    }elseif ("$attribute_code" == "items_package") {
                        $items_package = $items_packagearry[$value_value];
                        //$items_package = attribute($Mazentop,$attribute_code,$value_value);//打包方式
                        $zuzhuangarrary['items_package'] =  $items_package;
                        echo "打包方式$items_package\n";
                    }elseif ("$attribute_code" == "type") {
                        //$country_type = attribute($Mazentop,$attribute_code,$value_value);//国家
                        $country_type = $country_typearry[$value_value];
                        echo "国家$country_type\n";
                       if("$country_type" !== "All"){
                        $zuzhuangarrary['country_type'] =  $country_type;
                       }
                        
                    }elseif ("$attribute_code" == "grade") {
                        $grade = $gradearry[$value_value];
                        //$grade = attribute($Mazentop,$attribute_code,$value_value);//等级
                        $zuzhuangarrary['grade'] =  $grade;
                        echo "等级$grade\n";
                    }elseif ("$attribute_code" == "lace_size") {
                        $lace_size = $lace_sizearry[$value_value];
                        echo "改前lace_size".$lace_size."\n";
                        //$lace_size = attribute($Mazentop,$attribute_code,$value_value);//lace尺寸
                        if(strpos($lace_size,'4X4') !== false){
                                $zuzhuangarrary['lace_size'] =  "4\" x 4\"";
                            }elseif (strpos($lace_size,'4*4') !== false) {
                                $zuzhuangarrary['lace_size'] =  "4\" x 4\"";
                            }elseif (strpos($lace_size,'4X13') !== false) {
                                $zuzhuangarrary['lace_size'] =  "4\" x 13\"";
                            }elseif (strpos($lace_size,'4*13') !== false) {
                                $zuzhuangarrary['lace_size'] =  "4\" x 13\"";
                            }elseif (strpos($lace_size,'6X13') !== false) {
                                $zuzhuangarrary['lace_size'] =  "6\" x 13\"";
                            }elseif (strpos($lace_size,'6*13') !== false) {
                                $zuzhuangarrary['lace_size'] =  "6\" x 13\"";
                            }elseif (strpos($lace_size,'3*12') !== false) {
                                $zuzhuangarrary['lace_size'] =  "3\" x 12\"";
                            }elseif (strpos($lace_size,'3X12') !== false) {
                                $zuzhuangarrary['lace_size'] =  "3\" x 12\"";
                            }elseif (strpos($lace_size,'6x13 bob wig') !== false) {
                                $zuzhuangarrary['lace_size'] =  "6\" x 13\" bob";
                            }elseif (strpos($lace_size,'360 bob') !== false) {
                                $zuzhuangarrary['lace_size'] = "bob 360 wig";
                            }elseif (strpos($lace_size,'full bob') !== false) {
                                $zuzhuangarrary['lace_size'] = "bob full lace wig";
                            }else{
                                $zuzhuangarrary['lace_size'] = $lace_size;
                            }
                            //以下为透明或特殊lace_size避过上方的匹配
						$lacesize=strtolower(preg_replace('# #','',$lace_size));
                        if(strpos($lacesize,'transparent4*13lacewig'!== false)){
							$zuzhuangarrary['lace_size'] ='transparent 4*13 lace wig';
						}
                        else if(strpos($lacesize,'transparent4*4wig')!== false
							|| strpos($lacesize,'4*4BobWig')!== false)
						{
							$zuzhuangarrary['lace_size'] =$lace_size;
						}
                        echo "lace尺寸$lace_size\n";
                    }elseif ("$attribute_code" == "color") {
                        $color = $colorarry[$value_value];
                        //$color = attribute($Mazentop,$attribute_code,$value_value);//颜色
                        echo "颜色$color\n";//2019.07.09 修改 上边没有颜色取下边
                       if("$color" !== "Colored"){
                           $zuzhuangarrary['color'] =  addslashes($color);
                       }                       
                    }elseif ("$attribute_code" == "density") {
                        $density = $densityarry[$value_value];
                        //$density = attribute($Mazentop,$attribute_code,$value_value);//密度 
                       echo "密度$density\n";
                        $zuzhuangarrary['density'] =  addslashes($density);
                    }elseif("$attribute_code" == "cap_size"){
                        //发冒大小
                        if (!empty($sizearry)) {
                           $size = $sizearry[$value_value];
                        }else{
                            $size = $value_value;
                        }
                         $zuzhuangarrary['size'] =  addslashes($size);
                         echo "cap_size大小$size\n";
                    }elseif ("$attribute_code" == "wig_type") {
                        $wig_type = attribute($Mazentop,$attribute_code,$value_value);
                        $zuzhuangarrary['wig_type'] =  addslashes($wig_type);
                    }elseif ("$attribute_code" == "image") {//图片
                        $zuzhuangarrary['image'] =  addslashes($value_value);
                    }

                }
                //处理 参数不存在问题  lace_size
                $if_is_str = array_key_exists('lace_size', $zuzhuangarrary);
                        if($if_is_str == 0){
                            echo " lace size 不存在 设置为空\n";
                            $zuzhuangarrary['lace_size'] =  '';
                        }else{
                            echo "lace size 存在 \n";
                        }
                $post_arr = postsku_getproductopptionid($zuzhuangarrary,$Mazentop,$sku,$db,$storeid_sku);
                //print_r($post_arr);
                //此处主要是解决，网站更改产品属性后 旧的属性会丢失。
                if(!empty($post_arr['part_design_option_id']) || !empty($post_arr['Closure_inch_option_id']) || !empty($post_arr['Weft_inc_option_id']) || !empty($post_arr['Stretched_inc_option_id']) || !empty($post_arr['country_type_option_id']) || !empty($post_arr['density_option_id']) || !empty($post_arr['color_option_id']) || !empty($post_arr['length_option_id'])){
                // 如果四个 id 全是空，不记录。
                Getinsert($arrData=$post_arr,$table='dlz_product_attr'.'_'.$id_m,$db,$sync_data="0");//存储产品
                //Getinsert($arrData=$post_arr,$table='dlz_product_attr',$db,$sync_data="0");
                }
                //print_r($zuzhuangarrary);
            }

        }

     echo "++++++++++++++++++end++++++++++++++++++++\n"  ; 

}

//通过code  提取信息
function attribute($Mazentop,$attribute_code,$value_value){
    echo "$attribute_code\n";
        $Attribute = $Mazentop->getproductAttributeCode($attribute_code);
        $label ='Natural Color';
        foreach ($Attribute as $key_attr => $value_attr) {
                $texture_label = $value_attr['label'];
                $texture_value = $value_attr['value'];
                if($value_value == $texture_value){
                    $label = $texture_label;
                } 
            }

            return $label;
        
}

//通过sku 获取产品属性
function postsku_getproductopptionid($zuzhuangarrary,$Mazentop,$sku,$db,$storeid_sku){
    echo "******get option id*******\n";
    $product_optionid = $Mazentop->getproductExtensionAttr($sku="$sku");
    if(!empty($product_optionid['message']) ? $product_optionid['message'] : null) {
        echo $product_optionid['message']."\n";
        return false;
      }
    $options = $product_optionid['options'];//产品 options
    foreach ($options as $key => $value) {
               $product_sku = $value['product_sku'];//sku
               $title = trim(strtolower($value['title']));//属性名称
		echo '<pre>产品属性:'; print_r([$sku,$title]); echo '</pre>';
               $sort_order = $value['sort_order'];//订单分类id
               $is_require = $value['is_require'];//
               $getoption_id = $value['option_id'];//id
               $option_values = $value['values'];//id
               /*****增加Select 功能 在以下添加title=*******/
               if("$title" == "part design"){
                echo "----------Part Design--------------\n";
                $zuzhuangarrary['part_design_option_id'] = $getoption_id;
                   gettitle($getoption_id,$option_values,$field="part_design_option_id",$db,$table="dlz_product_partdesign",$storeid_sku);//
              }elseif ("$title" == "hair closure length/inch") {
                 echo "----------Hair Closure Length/inch--------------\n";
                 $zuzhuangarrary['Closure_inch_option_id'] = $getoption_id;
                   gettitle($getoption_id,$option_values,$field="Closure_inch_option_id",$db,$table="dlz_product_closureinch",$storeid_sku);//
              }elseif ("$title" == "hair weft length/inch") {
                 echo "----------Hair Weft Length/inch--------------\n";
                 $zuzhuangarrary['Weft_inc_option_id'] = $getoption_id;
                   gettitle($getoption_id,$option_values,$field="Weft_inc_option_id",$db,$table="dlz_product_weftinc",$storeid_sku);//
               }elseif ("$title" =="stretched length/inch") {
                echo "----------Stretched Length/Inch-------------\n";
                $zuzhuangarrary['Stretched_inc_option_id'] = $getoption_id;
                  gettitle($getoption_id,$option_values,$field="Stretched_inc_option_id",$db,$table="dlz_product_stretchedinc",$storeid_sku);//
               }elseif ("$title" == "type") {
                echo "----------Type-------------\n";
                $zuzhuangarrary['country_type_option_id'] = $getoption_id;
                   gettitle($getoption_id,$option_values,$field="country_type_option_id",$db,$table="dlz_product_countrytype",$storeid_sku);//
               }elseif("$title" == "density"){
                echo "----------density-------------\n";
                $zuzhuangarrary['density_option_id'] = $getoption_id;
                    gettitle($getoption_id,$option_values,$field="density_option_id",$db,$table="dlz_product_density",$storeid_sku);//2017/11/1
               }elseif ("$title" == "color") {
                echo "----------color-------------\n";
                    $zuzhuangarrary['color_option_id'] = $getoption_id;
                    gettitle($getoption_id,$option_values,$field="color_option_id",$db,$table="dlz_product_color",$storeid_sku);//2019/04/10
               }elseif ("$title" == "length/inch") {
                    echo "----------Length/inch-------------\n";
                 $zuzhuangarrary['length_option_id'] = $getoption_id;
                   gettitle($getoption_id,$option_values,$field="length_option_id",$db,$table="dlz_product_length",$storeid_sku);//
               }
           }
           return $zuzhuangarrary;
}


//获取一个option  id 下的 所有信息
function gettitle($getoption_id,$option_values,$field,$db,$table,$storeid_sku){
    $table_table = $table;
    //$filed_optionid = array();
    //$filed_optionid['storeid_sku'] = $storeid_sku;
    //$filed_optionid[$field] = $getoption_id;
//插入 optionid
    //Getinsert($arrData=$filed_optionid,$table='dlz_product_attr',$db,$sync_data="0");
    $option_arrary = array();
    $UpdateTime = date('Y-m-d H:i:s');
    foreach ($option_values as $key_r => $value_r) {
            
            $option_arrary['UpdateTime'] = $UpdateTime; 
            $values_title = $value_r['title'];
            $option_arrary['title'] = $values_title;
            $values_price = $value_r['price'];
            $option_arrary['price'] = $values_price;
            $values_option_type_id = $value_r['option_type_id'];
            $option_arrary['storeid_sku'] = $storeid_sku.'-'.$values_option_type_id;
            $option_arrary['option_type_id'] = $values_option_type_id;
            echo "-------$values_title ---- $values_option_type_id-----------\n";
            Getinsert($arrData=$option_arrary,$table=$table_table,$db,$sync_data="0");
        }

        
        //print_r($option_arrary);
}

$db = null;
